package com.yuba.front.event.handle;

import com.yuba.common.json.utils.JsonUtils;
import com.yuba.common.sse.dto.SseMessageDto;
import com.yuba.common.sse.utils.SseMessageUtils;
import com.yuba.front.domain.FrontMessage;
import com.yuba.front.event.MessageHandleEvent;
import com.yuba.front.event.UnMessageHandleEvent;
import com.yuba.front.service.IFrontMessageService;
import com.yuba.front.service.IFrontUserService;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 处理消息事件
 */
@Component
public class MessageEventHandler {

    private final IFrontMessageService frontMessageService;
    private final IFrontUserService userService;

    public MessageEventHandler(IFrontMessageService frontMessageService, IFrontUserService userService) {
        this.frontMessageService = frontMessageService;
        this.userService = userService;
    }

    /**
     * 标识符
     * @param type 消息类型
     * @param message 消息
     * @param pull 是否拉取数据
     */
    public record MessageResponse(String type, String message, Boolean pull) {}

    /**
     * 处理消息通知逻辑
     *
     * @param event 事件源
     */
    @Async
    @EventListener
    public void handleMessageEvent(MessageHandleEvent event) {
        String firstType = event.getType();

        FrontMessage frontMessage = new FrontMessage();
        frontMessage.setType(event.getType());
        frontMessage.setUserId(event.getUserId());
        frontMessage.setSenderId(event.getSenderId());
        frontMessage.setSourceId(event.getSourceId());
        frontMessage.setValue(event.getMessage());
        frontMessage.setMeta(JsonUtils.toJsonString(event.getMeta()));

        // 封装数据
        MessageResponse messageResponse = new MessageResponse(firstType, event.getSenderNickname() + event.getMessage(), true);

        frontMessageService.save(frontMessage);

        SseMessageDto sseMessageDto = new SseMessageDto();
        sseMessageDto.setUserIds(List.of(event.getUserId()));
        sseMessageDto.setMessage(JsonUtils.toJsonString(messageResponse));
//        SseMessageUtils.publishMessage(sseMessageDto);
        SseMessageUtils.sendMessage(event.getUserId(), JsonUtils.toJsonString(messageResponse));
    }


    @Async
    @EventListener
    public void unMessageEvent(UnMessageHandleEvent event) {
        // 取消消息数据
        frontMessageService.removeByUserIdAndSenderIdAndSourceIdAndType(event.getUserId(), event.getSenderId(), event.getSourceId(), event.getType());
    }
}
